package net.learn2develop.DB;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.learn2develop.GPS.R;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class DatabaseHelper extends SQLiteOpenHelper {

	public static final String DATABASE_NAME = "searching_places";
	
	protected Context context;
	
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, 1);
		this.context = context;
	}

	public void onCreate(SQLiteDatabase db) {
		String s;
		try {
			//Crea las tablas desde XML
			db.execSQL(context.getResources().getString(R.string.create_table_category));
			db.execSQL(context.getResources().getString(R.string.create_table_subcategory));
			db.execSQL(context.getResources().getString(R.string.create_table_places));
			URL url = new URL("http://www.bawide.net/sqledu.xml");
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(new InputSource(url.openStream()));
			NodeList statements = doc.getElementsByTagName("statement");
			for (int i=0; i<statements.getLength(); i++) {
				s = statements.item(i).getChildNodes().item(0).getNodeValue();
				db.execSQL(s);
			}
		} catch (Throwable t) {
			Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
		}
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS category");
		db.execSQL("DROP TABLE IF EXISTS subcategory");
		db.execSQL("DROP TABLE IF EXISTS places");
		onCreate(db);
	}
	
	
	
}
